var crypto = require('crypto')
var variables = require('../../config/variables');
var jwt = require('jsonwebtoken');

/*
 * 
 * 根据盐值和秘钥进行加密
 * return 加密结果
 */
function hmac(content, privateKey, salt, algorithm) {

    if (!algorithm) {
        algorithm = 'sha256';
    }
    var shasum = crypto.createHmac(algorithm, privateKey);
    shasum.update(content);
    shasum.update(salt);

    // 加密结果
    return shasum.digest('hex');
}

module.exports = {
    // 生成密码加密密文
    genPasswordCipherText: function (content, salt) {
        console.log('content=%s', content);
        console.log('passwordPrivateKey=%s', variables.passwordPrivateKey);
        console.log('salt=%s', salt);
        return hmac(content, variables.passwordPrivateKey, salt);
    },
    getJwtSign: function (userInfo) {
        return jwt.sign(userInfo, variables.jwtSecretToken, {expiresIn: variables.jwtTokenExpiration});
    },
    //加密
    cipher: function (content,key, algorithm) {
        if(!algorithm){
            algorithm = "rc4";  // 可以加密和解密
        }
        var encrypted = "";
        var cip = crypto.createCipher(algorithm, key);
        encrypted += cip.update(content, 'utf8', 'hex');
        encrypted += cip.final('hex');
        return encrypted;
    },

    //解密
    decipher: function (content, key, algorithm) {
        if(!algorithm){
            algorithm = "rc4";  // 可以加密和解密
        }
        var decrypted = "";
        var decipher = crypto.createDecipher(algorithm, key);
        decrypted += decipher.update(content, 'hex', 'utf8');
        decrypted += decipher.final('utf8');
        return decrypted;
    }
}
